package net.mof.manual

import org.json.JSONException
import org.json.JSONObject

/**
 * Created by LiYueHui on 2020/2/2.
 *
 */

object Manual {

    @JvmStatic
    fun <T : Any> typeToJSONObject(type: T?): JSONObject {
        val retObj = JSONObject();
        if (type != null) {
            val annotations: Annotation? = type.javaClass.getAnnotation(JsonMark::class.java)
            if (annotations != null) {
                val tran = Class.forName(type.javaClass.name + "_json")
                val interfaceJson = tran.newInstance() as ITransformJson<T>
                return interfaceJson.typeToJSONObject(type)
            }
        }
        return retObj
    }

    @JvmStatic
    fun <T> jsonToType(input: String?, clazz: Class<T>?): T? {
        if (input != null && clazz != null && clazz.getAnnotation(JsonMark::class.java) != null) {
            val nClazz = Class.forName(clazz.name + "_json")
            val transform = nClazz.newInstance() as ITransformJson<T>
            return transform.jsonToType(input)
        }
        return null
    }

    @JvmStatic
    fun isJsonStr(msg: String?): Boolean {
        if (msg != null) {
            try {
                val json = JSONObject(msg)
                return true
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        return false
    }

    @JvmStatic
    fun isEmpty(str: CharSequence?): Boolean {
        return str == null || str.length == 0
    }


}